/**
 * 用户认证
 * sessionAuth
 *
 * @module      :: Policy
 * @description :: Simple policy to allow any authenticated user
 *                 Assumes that your login action in one of your controllers sets `req.session.authenticated = true;`
 * @docs        :: http://sailsjs.org/#!documentation/policies
 *
 */
module.exports = function(req, res, next) {
   var token;

  // User is allowed, proceed to the next policy,
  // or if this is the last policy, the controller
  if (req.session.authenticated) {
    return next();
  }

  // Look for token in query string
  if (req.query && req.query['accessToken']) {
      token = req.query['accessToken'];
  }
  // Look for token in post body
  else if (req.body && req.body['accessToken']) {
      token = req.body['accessToken'];
  }
  // Not found
  else
      return res.jsonResponse(404,'accessToken not found');

    if(token){
        AccessToken.findOne({accessToken:token})
            .exec(function(err, result) {
                if (err){
                    sails.log.error(err);
                    return res.jsonResponse(err);
                }
                else if (!result) {
                    return  res.jsonResponse(403,'Token not found or expired');
                }
                else if (!result.checkTTL()) {
                    return  res.jsonResponse(403,'Token already expired');
                }
                else {
                    return next();
                };
            });
    }else{
        // User is not allowed
        // (default res.forbidden() behavior can be overridden in `config/403.js`)
        return res.jsonResponse(403, 'Auth failure!');
    }
};